﻿using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Services;
using Ids4Review.AuthorizationServer.Data.Core;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Ids4Review.AuthorizationServer.Services
{
    public class ProfileService
        : IProfileService
    {
        private readonly UserManager<ApplicationUser> _userManager;
        public ProfileService(UserManager<ApplicationUser> userManager)
        {
            _userManager = userManager;
        }
        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var subject = context.Subject.Claims.SingleOrDefault(c => c.Type == JwtClaimTypes.Subject);
            if (subject == null)
            {
                throw new NullReferenceException("Subject id is not allowd to be null.");
            }
            var subjectId = subject.Value;
            var user = await _userManager.FindByIdAsync(subjectId);
            context.IssuedClaims =await GetClaimsFromUserAsync(user);
        }
        public async Task IsActiveAsync(IsActiveContext context)
        {
            var subject = context.Subject.Claims.SingleOrDefault(c => c.Type == JwtClaimTypes.Subject);
            if (subject == null)
            {
                throw new NullReferenceException("Subject id is not allowd to be null.");
            }
            var subjectId = subject.Value;
            var user = await _userManager.FindByIdAsync(subjectId);
            context.IsActive = user != null;
        }
        private async Task<List<Claim>> GetClaimsFromUserAsync(ApplicationUser user)
        {
            var claims = new List<Claim>();
            claims.Add(new Claim(JwtClaimTypes.Subject, user.Id.ToString()));
            claims.Add(new Claim(JwtClaimTypes.PreferredUserName, user.UserName));
            claims.Add(new Claim("avatar", user.Avatar));
            var roles = await _userManager.GetRolesAsync(user);
            foreach (var item in roles)
            {
                claims.Add(new Claim(JwtClaimTypes.Role, item));
            }
            return claims;
        }
    }
}
